﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DSAServer.Models;
using DSAServer.Models.Input;
using DSAServer.Models.Output;
using DSAServer.Utils;

namespace DSAServer.Service
{
    public class OrderService
    {
        public InvokeResult Insert(TaobaoOrderInfo taobaoOrderInfo)
        {
            InvokeResult result = new InvokeResult();
            try
            {
                using (var context = DbUtils.Main.UseTransaction(true))
                {
                    context.Sql("insert into trade(no,buyernick,buyermessage,receivername,receiveraddress,receivermobile,num,totalfee,status,created,source) values(@0,@1,@2,@3,@4,@5,@6,@7,@8,@9,@10)"
                   , taobaoOrderInfo.no, taobaoOrderInfo.buyernick, taobaoOrderInfo.buyermessage, taobaoOrderInfo.receivername, taobaoOrderInfo.receiveraddress,
                   taobaoOrderInfo.receivermobile, taobaoOrderInfo.num, taobaoOrderInfo.totalfee, taobaoOrderInfo.status, taobaoOrderInfo.created, taobaoOrderInfo.Source).Execute();
                    foreach (TaobaoSunOrderInfo order in taobaoOrderInfo.orders)
                    {
                        context.Sql("insert into orders(ono,oid,title,producttype,skupropertiesname,picpaper,packagetype,num,payment,status,createtime,source) values(@0,@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11)"
                       , taobaoOrderInfo.no, order.oid, order.title, order.producttype, order.skupropertiesname, order.picpaper, order.packagetype, order.num, order.payment, order.status, DateTime.Now, order.Source).Execute();
                    }
                    context.Commit();
                    result.ok = true;
                    LogUtil.Info(DateTime.Now + ":订单数据插入数据库成功");
                }
            }
            catch (Exception ex)
            {
                LogUtil.Info(DateTime.Now + ":订单数据插入数据库失败" + ex.Message);
            }
            if (!result.ok)
            {
                result.msg = "添加订单失败!";
            }
            return result;
        }

        public InvokeResult InsertWeidianOrder(TradeInfo tradeInfo, List<DSAServer.Models.Input.OrderInfo> orderInfoList)
        {
            InvokeResult result = new InvokeResult();
            try
            {
                using (var context = DbUtils.Main.UseTransaction(true))
                {
                    context.Sql("insert into trade(no,buyernick,buyermessage,receivername,receiveraddress,receivermobile,num,totalfee,status,created,source) values(@0,@1,@2,@3,@4,@5,@6,@7,@8,@9,@10)"
                   , tradeInfo.no, tradeInfo.buyernick, tradeInfo.buyermessage, tradeInfo.receivername, tradeInfo.receiveraddress,
                   tradeInfo.receivermobile, tradeInfo.num, tradeInfo.totalfee, tradeInfo.status, tradeInfo.created, tradeInfo.source).Execute();
                    foreach (DSAServer.Models.Input.OrderInfo orderInfo in orderInfoList)
                    {
                        context.Sql("insert into orders(ono,oid,title,producttype,skupropertiesname,picpaper,packagetype,num,payment,status,createtime,source,uploadtype,imgurl) values(@0,@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12,@13)"
                       , tradeInfo.no, orderInfo.oid, orderInfo.title, orderInfo.producttype, orderInfo.skupropertiesname, orderInfo.picpaper, orderInfo.packagetype, orderInfo.num, orderInfo.payment, orderInfo.status, DateTime.Now,
                       orderInfo.source, orderInfo.uploadtype, orderInfo.imgurl).Execute();
                    }
                    context.Commit();
                    result.ok = true;
                    LogUtil.Info(DateTime.Now + ":订单数据插入数据库成功");
                }
            }
            catch (Exception ex)
            {
                LogUtil.Info(DateTime.Now + ":订单数据插入数据库失败" + ex.Message);
            }
            if (!result.ok)
            {
                result.msg = "添加订单失败!";
            }
            return result;
        }

        //public InvokeResult UpdateOrderUploadStatse(string no)
        //{
        //    InvokeResult result = new InvokeResult();
        //    result.ok = DbUtils.Main.Update("trade")
        //        .Column("trade", "")
        //        .Where("", "")
        //        .Execute() > 0;
        //    return result;
        //}

        public InvokeResult InsertImage(ImageSubmitInfo imageSubmitInfo)
        {
            InvokeResult result = new InvokeResult();
            DbUtils.Main.Sql("insert into orderimage(oid,pid,url,num) values(@0,@1,@2,@3)", imageSubmitInfo.oid, imageSubmitInfo.pid, imageSubmitInfo.url, imageSubmitInfo.num).Execute();
            result.ok = true;
            return result;
        }

        public InvokeResult UpdateTrade(string no)
        {
            InvokeResult result = new InvokeResult();
            result.ok = DbUtils.Main.Sql("update trade set hasupload=1 where no=@0", no).Execute() > 0;
            return result;
        }

        public InvokeResult UpdateTrade(string no, List<ImageSubmitInfo> imageSubmitInfoList)
        {
            InvokeResult result = new InvokeResult();
            try
            {
                using (var context = DbUtils.Main.UseTransaction(true))
                {
                    foreach (var imageSubmitInfo in imageSubmitInfoList)
                    {
                        context.Sql("insert into orderimage(oid,pid,url,num) values(@0,@1,@2,@3)", imageSubmitInfo.oid, imageSubmitInfo.pid, imageSubmitInfo.url, imageSubmitInfo.num).Execute();
                    }
                    context.Sql("update trade set hasupload=1 where no=@0", no).Execute();
                    context.Commit();
                }
                result.ok = true;
            }
            catch (Exception ex)
            {
                result.ok = false;
                LogUtil.Info(DateTime.Now + ":" + ex.Message);
            }
            return result;
        }

        public bool ExistOrder(string tid)
        {
            return DbUtils.Main.Sql("select count(*) from trade where no=@0", tid).QuerySingle<int>() > 0;
        }

        //public TaobaoOrderInfo GetOrderData(string tid, string buyernick)
        //{
        //    TaobaoOrderInfo result = new TaobaoOrderInfo();
        //    try
        //    {
        //        result = DbUtils.Main.Sql("select * from trade where no=@0 and buyernick=@1", tid, buyernick).QuerySingle<TaobaoOrderInfo>();
        //        if (!result.hasupload)
        //        {
        //            result.orders = new List<TaobaoSunOrderInfo>();
        //            result.orders = DbUtils.Main.Sql("select  ono as no,oid,title,producttype,skupropertiesname,picpaper,num,payment,status from orders where ono=@0", tid).QueryMany<TaobaoSunOrderInfo>();
        //        }
        //        else
        //        {
        //            result = null;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        result = null;
        //    }
        //    return result;
        //}

        public List<TaobaoSunOrderInfo> GetOrderData(string tid, string buyernick)
        {
            List<TaobaoSunOrderInfo> result = new List<TaobaoSunOrderInfo>();
            try
            {
                bool hasupload = DbUtils.Main.Sql("select hasupload from trade where no=@0 and buyernick=@1", tid, buyernick).QuerySingle<bool>();
                if (!hasupload)
                    result = DbUtils.Main.Sql("select ono as no, oid,title,producttype,skupropertiesname,picpaper,num,payment,status from orders where ono=@0", tid).QueryMany<TaobaoSunOrderInfo>();
                else
                    result = null;
            }
            catch (Exception ex)
            {
                result = null;
            }
            return result;
        }
        public InvokeResult<PageEntity<DSAServer.Models.Output.OrderInfo>> QueryUnDownlaodOrders(PageRequest pageRequest)
        {
            LogUtil.Info("开始查询");
            InvokeResult<PageEntity<DSAServer.Models.Output.OrderInfo>> result = new InvokeResult<PageEntity<DSAServer.Models.Output.OrderInfo>>();
            try
            {
                PageEntity<DSAServer.Models.Output.OrderInfo> data = new PageEntity<DSAServer.Models.Output.OrderInfo>();
                data.PageSize = pageRequest.pageSize;
                data.PageNo = pageRequest.pageNo;
                string whereStr = "hasdownload=0  ";
                List<object> args = new List<object>();
                string order = pageRequest.order;
                if (string.IsNullOrEmpty(order))
                    order = "created desc";
                pageRequest.conds = pageRequest.conds ?? "";
                var conds = pageRequest.conds.Split('|');
                foreach (var cond in conds)
                {
                    if (cond.Split(':').Length != 2) continue;
                    var key = cond.Split(':')[0];
                    var val = cond.Split(':')[1];
                    switch (key)
                    {
                        case "source":
                            whereStr += " and source =  @" + args.Count;
                            args.Add(val);
                            break;
                        case "orderno":
                            whereStr += " and no like @" + args.Count;
                            args.Add("%" + val + "%");
                            break;
                        case "wangwang":
                            whereStr += " and buyernick like @" + args.Count;
                            args.Add("%" + val + "%");
                            break;
                        case "time1":
                            whereStr += " and created>=@" + args.Count;
                            args.Add(val);
                            break;
                        case "time2":
                            whereStr += " and created<=@" + args.Count;
                            args.Add(val);
                            break;
                    }
                }


                data.RecordCount =
                   DbUtils.Main.Sql("SELECT count(*) from trade where " + whereStr, args.ToArray()).QuerySingle<int>();
                data.Records.AddRange(DbUtils.Main.Select<DSAServer.Models.Output.OrderInfo>(@"no,buyernick as wangwang,num,created as time,hasdownload,downloadtime,hassend,sendtime,source")
                                     .From("trade")
                                     .Where(whereStr)
                                     .Paging(pageRequest.pageNo, pageRequest.pageSize)
                                     .Parameters(args.ToArray())
                                     .OrderBy(order)
                                     .QueryMany());
                foreach (var info in data.Records)
                {
                    info.details = DbUtils.Main.Sql("SELECT oid AS NO, title AS NAME, producttype AS type, skupropertiesname AS size, picpaper AS paper, num,packagetype,uploadtype FROM orders WHERE ono = @0 ", info.no).QueryMany<OrderDetail>();//AND picpaper IN ( '富士晶彩绒面', '富士晶彩光面', '柯达晶彩绒面', '柯达晶彩光面','柯达金尊光面' )
                    foreach (var detail in info.details)
                    {
                        detail.images =
                            DbUtils.Main.Sql(@"SELECT a.url ,a.num,b.sellerCut,b.IsCut,b.tubW,b.tubH,b.Width,b.Height,b.WidgetWidth,b.WidgetHeight,b.BeginX,b.BeginY,b.EndX,b.EndY,b.Rotate as rotateangle,b.X,b.Y,b.CutW,b.CutH from orderimage a                                            left JOIN orderimageattr b on a.pid = b.pid  where a.oid=@0", detail.no).
                                QueryMany<OrderImage>();
                    }
                }
                result.data = data;
                result.ok = true;
            }
            catch (Exception ex)
            {
                LogUtil.Info(ex.Message);
            }
            return result;
        }

        public InvokeResult<PageEntity<DSAServer.Models.Output.OrderInfo>> QueryHasDownlaodOrders(PageRequest pageRequest)
        {
            InvokeResult<PageEntity<DSAServer.Models.Output.OrderInfo>> result = new InvokeResult<PageEntity<DSAServer.Models.Output.OrderInfo>>();

            PageEntity<DSAServer.Models.Output.OrderInfo> data = new PageEntity<DSAServer.Models.Output.OrderInfo>();
            data.PageSize = pageRequest.pageSize;
            data.PageNo = pageRequest.pageNo;
            string whereStr = "hasdownload=1 ";
            List<object> args = new List<object>();
            string order = pageRequest.order;
            if (string.IsNullOrEmpty(order))
                order = "created desc";

            pageRequest.conds = pageRequest.conds ?? "";
            var conds = pageRequest.conds.Split('|');
            foreach (var cond in conds)
            {
                if (cond.Split(':').Length != 2) continue;
                var key = cond.Split(':')[0];
                var val = cond.Split(':')[1];
                switch (key)
                {
                    case "source":
                        whereStr += " and source =  @" + args.Count;
                        args.Add(val);
                        break;
                    case "orderno":
                        whereStr += " and no like @" + args.Count;
                        args.Add("%" + val + "%");
                        break;
                    case "wangwang":
                        whereStr += " and buyernick like @" + args.Count;
                        args.Add("%" + val + "%");
                        break;
                    case "time1":
                        whereStr += " and created>=@" + args.Count;
                        args.Add(val);
                        break;
                    case "time2":
                        whereStr += " and created<=@" + args.Count;
                        args.Add(val);
                        break;
                }
            }

            data.RecordCount =
               DbUtils.Main.Sql("SELECT count(*) from trade where " + whereStr, args.ToArray()).QuerySingle<int>();
            data.Records.AddRange(DbUtils.Main.Select<DSAServer.Models.Output.OrderInfo>(@"no,buyernick as wangwang,num,created as time,hasdownload,downloadtime,hassend,sendtime,source")
                                 .From("trade")
                                 .Where(whereStr)
                                 .Paging(pageRequest.pageNo, pageRequest.pageSize)
                                 .Parameters(args.ToArray())
                                 .OrderBy(order)
                                 .QueryMany());
            foreach (var info in data.Records)
            {
                info.details = DbUtils.Main.Sql("SELECT oid AS NO, title AS NAME, producttype AS type, skupropertiesname AS size, picpaper AS paper, num FROM orders WHERE ono = @0 ", info.no).QueryMany<OrderDetail>();//AND picpaper IN ( '富士晶彩绒面', '富士晶彩光面', '柯达晶彩绒面', '柯达晶彩光面','柯达金尊光面' )
                foreach (var detail in info.details)
                {
                    detail.images =
                        DbUtils.Main.Sql(@"SELECT a.url ,a.num,b.sellerCut,b.IsCut,b.tubW,b.tubH,b.Width,b.Height,b.WidgetWidth,b.WidgetHeight,b.BeginX,b.BeginY,b.EndX,b.EndY,b.Rotate as rotateangle,b.X,b.Y,b.CutW,b.CutH from orderimage a
                                            left JOIN orderimageattr b on a.pid = b.pid where a.oid=@0", detail.no).
                            QueryMany<OrderImage>();
                }
            }
            result.data = data;
            result.ok = true;
            return result;
        }

        //public InvokeResult SetOrderHasDown(List<string> ids)
        //{
        //    InvokeResult result = new InvokeResult();
        //    using (var context = DbUtils.Main.UseTransaction(true))
        //    {
        //        foreach (var id in ids)
        //        {
        //            context.Sql("update trade set hasdownload=1,downloadtime=sysdate() where no=@0", id).Execute();

        //            PageEntity<OrderInfo> data = new PageEntity<OrderInfo>();
        //            data.PageSize = pageRequest.pageSize;
        //            data.PageNo = pageRequest.pageNo;
        //            string whereStr = "hasdownload=1";
        //            List<object> args = new List<object>();

        //            data.RecordCount =
        //               DbUtils.Main.Sql("SELECT count(*) from trade where " + whereStr, args.ToArray()).QuerySingle<int>();
        //            data.Records.AddRange(DbUtils.Main.Select<OrderInfo>(@"no,buyernick as wangwang,num,created as time,hasdownload,downloadtime")
        //                                 .From("trade")
        //                                 .Where(whereStr)
        //                                 .Paging(pageRequest.pageNo, pageRequest.pageSize)
        //                                 .Parameters(args.ToArray())
        //                                 .OrderBy("created desc")
        //                                 .QueryMany());
        //            foreach (var info in data.Records)
        //            {
        //                info.details = DbUtils.Main.Sql("SELECT oid AS NO, title AS NAME, producttype AS type, skupropertiesname AS size, picpaper AS paper, num FROM orders WHERE ono = @0 AND picpaper IN ( '富士晶彩绒面', '富士晶彩光面', '柯达晶彩绒面', '柯达晶彩光面' )", info.no).QueryMany<OrderDetail>();
        //                foreach (var detail in info.details)
        //                {
        //                    detail.images =
        //                        DbUtils.Main.Sql("SELECT url as imageurl,num from orderimage  where oid=@0", detail.no).
        //                            QueryMany<OrderImage>();
        //                }
        //            }
        //            result.data = data;
        //            result.ok = true;
        //            return result;
        //        }
        //    }
        //}

        public InvokeResult SetOrderHasDown(List<string> ids)
        {
            InvokeResult result = new InvokeResult();
            using (var context = DbUtils.Main.UseTransaction(true))
            {
                foreach (var id in ids)
                {
                    context.Sql("update trade set hasdownload=1,downloadtime=sysdate() where no=@0", id).Execute();
                }
                context.Commit();
            }
            result.ok = true;
            return result;
        }

        public InvokeResult SetOrderHasSend(List<string> ids)
        {
            InvokeResult result = new InvokeResult();
            using (var context = DbUtils.Main.UseTransaction(true))
            {
                foreach (var id in ids)
                {
                    context.Sql("update trade set hassend=1,sendtime=sysdate() where no=@0", id).Execute();
                }
                context.Commit();
            }
            result.ok = true;
            return result;
        }

        /// <summary>
        /// 查询微店未下载订单列表
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public InvokeResult<List<OrderDetail>> QueryUnUploadOrderInfoByMobile(string mobile)
        {
            InvokeResult<List<OrderDetail>> result = new InvokeResult<List<OrderDetail>>();

            //using (var context = DbUtils.Main.UseTransaction(true))
            //{
            result.data = DbUtils.Main.Sql(@"select b.no as ono, a.oid AS NO, a.title AS NAME, a.producttype AS type, a.skupropertiesname AS size, a.picpaper AS paper, a.num,a.packagetype,
                                a.imgurl,a.uploadtype,a.source,c.width/c.height as aspectRatio from orders a
                                left JOIN trade b on a.ono=b.`no`
                                left JOIN photosize c on a.skupropertiesname=c.`name` and a.producttype=c.picturetype
                                where b.hasupload=0 and b.source=1 and b.receivermobile=@0", mobile).QueryMany<OrderDetail>();
            //}

            result.ok = true;
            return result;
        }

        public InvokeResult SumbitOrderInfo(List<OrderDetail> orderPara)
        {
            LogUtil.Info("微店照片数据库操作" + JsonHelper.SerializeObject(orderPara));
            InvokeResult result = new InvokeResult();
            using (var context = DbUtils.Main.UseTransaction(true))
            {
                foreach (OrderDetail orderDetail in orderPara)
                {
                    context.Update("trade")
                       .Column("hasupload", true)
                       .Where("no", orderDetail.ono)
                       .Execute();
                    foreach (OrderImage oi in orderDetail.images)
                    {
                        var pid = Guid.NewGuid().ToString().Replace("-", "");
                        context.Insert("orderimage")
                               .Column("oid", orderDetail.no)
                               .Column("pid", pid)
                               .Column("url", oi.url)
                               .Column("serverid", oi.serverid)
                               .Column("num", oi.num)
                               .Execute();
                        context.Insert("orderimageattr")
                               .Column("oid", orderDetail.no)
                               .Column("pid", pid)
                               .Column("sellerCut", oi.sellerCut)
                               .Column("IsCut", oi.IsCut)
                               .Column("tubW", oi.tubW)
                               .Column("tubH", oi.tubH)
                               .Column("Width", oi.Width)
                               .Column("Height", oi.Height)
                               .Column("WidgetWidth", oi.WidgetWidth)
                               .Column("WidgetHeight", oi.WidgetHeight)
                               .Column("BeginX", oi.BeginX)
                               .Column("BeginY", oi.BeginY)
                               .Column("EndX", oi.EndX)
                               .Column("EndY", oi.EndY)
                               .Column("Rotate", oi.rotateangle)
                               .Column("X", oi.X)
                               .Column("Y", oi.Y)
                               .Column("CutW", oi.CutW)
                               .Column("CutH", oi.CutH)
                               .Execute();
                    }
                }
                result.ok = true;
                context.Commit();
            }
            return result;
        }
    }
}